﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;
using ERP_SaaS_WinForm.生产计划_派单_车间.CarManage;
using ERP_SaaS_WinForm.生产计划_派单_车间.apiResquest;

namespace ERP_SaaS_WinForm.生产计划_派单_车间
{
    public partial class SelectCar : Form
    {
        private DataGridView dgvCars;
        private TextBox txtSearch;
        private Button btnSearch;
        private Button btnSelect;
        private Button btnCancel;
        private List<CarData> carList;
        private HttpClient httpClient;

        public SelectCar()
        {
            InitializeComponent();
            InitializeCustomComponents();
            LoadCarData();
        }

        private void InitializeCustomComponents()
        {
            // 设置窗体属性
            this.Size = new Size(800, 600);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Text = "选择车间";

            // 创建控件
            dgvCars = new DataGridView();
            txtSearch = new TextBox();
            btnSearch = new Button();
            btnSelect = new Button();
            btnCancel = new Button();

            // 设置搜索区域
            Panel searchPanel = new Panel();
            searchPanel.Dock = DockStyle.Top;
            searchPanel.Height = 50;
            searchPanel.Padding = new Padding(10);

            Label lblSearch = new Label();
            lblSearch.Text = "搜索:";
            lblSearch.Location = new Point(10, 15);
            lblSearch.AutoSize = true;

            txtSearch.Location = new Point(60, 12);
            txtSearch.Size = new Size(200, 23);

            btnSearch.Text = "搜索";
            btnSearch.Location = new Point(270, 10);
            btnSearch.Size = new Size(60, 25);
            btnSearch.Click += BtnSearch_Click;

            searchPanel.Controls.AddRange(new Control[] { lblSearch, txtSearch, btnSearch });

            // 设置按钮区域
            Panel buttonPanel = new Panel();
            buttonPanel.Dock = DockStyle.Bottom;
            buttonPanel.Height = 50;
            buttonPanel.Padding = new Padding(10);

            btnSelect.Text = "选择";
            btnSelect.Location = new Point(600, 10);
            btnSelect.Size = new Size(60, 25);
            btnSelect.Click += BtnSelect_Click;

            btnCancel.Text = "取消";
            btnCancel.Location = new Point(670, 10);
            btnCancel.Size = new Size(60, 25);
            btnCancel.Click += BtnCancel_Click;

            buttonPanel.Controls.AddRange(new Control[] { btnSelect, btnCancel });

            // 设置DataGridView
            dgvCars.Dock = DockStyle.Fill;
            dgvCars.AllowUserToAddRows = false;
            dgvCars.AllowUserToDeleteRows = false;
            dgvCars.ReadOnly = true;
            dgvCars.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvCars.MultiSelect = false;
            dgvCars.CellDoubleClick += DgvCars_CellDoubleClick;

            // 添加控件到窗体
            this.Controls.Add(dgvCars);
            this.Controls.Add(searchPanel);
            this.Controls.Add(buttonPanel);

            // 初始化HttpClient
            httpClient = new HttpClient();
        }

        private async void LoadCarData()
        {
            try
            {
                var response = await ApiRequestHelper.GetAsync<ApiCarInfoResponse>("api/Car/GetCar");
                
                if (response.Success && response.Data?.code == 200 && response.Data.data != null)
                {
                    carList = response.Data.data;
                    SetupDataGridView();
                    LoadDataToGrid();
                }
                else
                {
                    var errorMsg = response.Data?.msg ?? response.Message;
                    ApiRequestHelper.ShowError($"获取车间数据失败: {errorMsg}");
                }
            }
            catch (Exception ex)
            {
                ApiRequestHelper.ShowError($"加载车间数据时出错: {ex.Message}");
            }
        }

        private void SetupDataGridView()
        {
            dgvCars.Columns.Clear();
            dgvCars.AutoGenerateColumns = false;

            dgvCars.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "CarCode",
                HeaderText = "车间编号",
                Width = 100
            });

            dgvCars.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "CarName",
                HeaderText = "车间名称",
                Width = 150
            });

            dgvCars.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "CarArea",
                HeaderText = "车间面积",
                Width = 100
            });

            dgvCars.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "Leader",
                HeaderText = "负责人",
                Width = 100
            });
        }

        private void LoadDataToGrid()
        {
            if (carList != null)
            {
                dgvCars.DataSource = carList;
            }
        }

        private void BtnSearch_Click(object sender, EventArgs e)
        {
            if (carList != null)
            {
                var filteredList = carList.Where(c => 
                    string.IsNullOrEmpty(txtSearch.Text) ||
                    (c.CarCode?.ToLower().Contains(txtSearch.Text.ToLower()) == true) ||
                    (c.CarName?.ToLower().Contains(txtSearch.Text.ToLower()) == true) ||
                    (c.Leader?.ToLower().Contains(txtSearch.Text.ToLower()) == true)
                ).ToList();

                dgvCars.DataSource = filteredList;
            }
        }

        private void DgvCars_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                BtnSelect_Click(sender, e);
            }
        }

        private void BtnSelect_Click(object sender, EventArgs e)
        {
            if (dgvCars.CurrentRow != null)
            {
                SelectedCar = dgvCars.CurrentRow.DataBoundItem as CarData;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show("请选择一个车间", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        public CarData SelectedCar { get; private set; }
    }
}
